const hope = require("hope");

const { sign, verify } = require("./lib/index.js");

const confSymbol = Symbol("jwt#conf");

const PAYLOAD_DEFAULT_KEYS = ["exp", "nbf", "sub", "aud", "iss"];

hope.registerSrv(
	"hopeJWT",
	{
		// 加密算法
		alg: "HS256",
		// 密钥
		secret: "hope#jwt",
		// 证书
		cert: "",
		// 过期时间
		exp: Math.floor(Date.now() / 1000) + 60 * 60
	},
	function () {
		this.__init = function (opts) {
			let conf = {};

			conf.payload = {};

			PAYLOAD_DEFAULT_KEYS.forEach(item => {
				if (opts[item]) {
					conf.payload[item] = opts[item];
				}
			});

			conf.secretOrPrivateKey = opts.privateKey || opts.secret;

			conf.secretOrPublichKey = opts.publicKey || opts.secret;

			conf.alg = opts.alg || "HS256";

			this[confSymbol] = conf;
		};

		/**
		 * 签名
		 *
		 * @param {Hash} payload 载荷
		 *
		 * @return {Promise}
		 */
		this.sign = sign(confSymbol);
		/**
		 * 签证签名
		 *
		 * @param {String} token 待验证的签名字符串
		 *
		 * @return {Promise}
		 */
		this.verify = verify(confSymbol);
	}
);
